package conf

import (
	"encoding/json"
	"fmt"
	"sync"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type Config struct {
	Mysql *MYSQL
	App *App
}

func (c *Config) String() string {
	data, _ := json.Marshal(c)
	return string(data)

}

func DefaultConfig() *Config {
	return &Config{
		Mysql: &MYSQL{
			Host:     "127.0.0.1",
			Port:     3306,
			DB:       "vblog",
			Username: "xiaowei",
			Password: "123456",
		},
		App: &App{
			HttpHost: "127.0.0.1",
			HttpPort: 8888,
		},
	}
}

type MYSQL struct {
	Host     string `json:"host" toml:"host" env:"MYSQL_HOST"`
	Port     int    `json:"port" toml:"port" env:"MYSQL_PORT"`
	DB       string `json:"database" toml:"database" env:"MYSQL_DB"`
	Username string `json:"username" toml:"username" env:"MYSQL_USERNAME"`
	Password string `json:"password" toml:"password" env:"MYSQL_PASSWORD"`

	// 连接数据库，保证单一连接
	conn *gorm.DB
	lock sync.Mutex
}


type App struct {
	HttpHost string `json:"http_host" env:"HTTP_HOST"`
	HttpPort int64  `json:"http_port" env:"HTTP_PORT"`
}


func (a *App) HttpAddr() string{
	return	fmt.Sprintf("%s:%d", a.HttpHost, a.HttpPort)
}

/***
  dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
  db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
***/

func (m *MYSQL) DSN() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		m.Username,
		m.Password,
		m.Host,
		m.Port,
		m.DB)
}

// 避免多个 goroutine 同时初始化 gorm.DB 连接
func (m *MYSQL) GetConn() *gorm.DB {
	// 第一重检查（无锁快速路径），大多数情况下连接已存在，可以避免不必要的锁开销
	if m.conn == nil {
		m.lock.Lock()
		defer m.lock.Unlock()

		// 第二重检查（加锁后确认）
		if m.conn == nil {
			conn, err := gorm.Open(mysql.Open(m.DSN()), &gorm.Config{})
			if err != nil {
				panic(err)
			}
			m.conn = conn
		}
	}
	return m.conn
}
